package com.yanyu.space.common.log.support;

import com.yanyu.space.common.core.util.AppContext;
import com.yanyu.space.common.log.handler.LogFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;

/**
 * @author gz
 */
@Slf4j
public class LogMessageInterceptor implements ChannelInterceptor {
    private Tracer tracer = AppContext.getBean(Tracer.class);
    @Override
    public Message<?> preSend(Message<?> msg, MessageChannel mc) {
        if(this.tracer.currentSpan() != null) {
            LogFactory.getInstance().start(this.tracer.currentSpan().context());
        }
        return msg;
    }

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
        LogFactory.getInstance().close();
    }
}
